package org.sunyaxing.transflow.transflowapp.controllers;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.sunyaxing.transflow.api.extensions.base.types.TransFlowInput;
import org.sunyaxing.transflow.api.extensions.base.types.TransFlowMiddleHandler;
import org.sunyaxing.transflow.api.extensions.base.types.TransFlowOutput;
import org.sunyaxing.transflow.transflowapp.common.Result;
import org.sunyaxing.transflow.transflowapp.config.HandlerProperties;
import org.sunyaxing.transflow.transflowapp.config.JobConfigProperties;
import org.sunyaxing.transflow.transflowapp.controllers.dtos.PluginListDto;
import org.sunyaxing.transflow.transflowapp.factory.PluginManager;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/transflow/plugins")
public class PluginsController {
    private static final Logger log = LoggerFactory.getLogger(PluginsController.class);

    public PluginsController() {
        log.info("loader is {}", PluginsController.class.getClassLoader());
    }

    @Autowired
    private PluginManager pluginManager;

    @GetMapping("/list")
    public Result<List<PluginListDto>> getPlugins() {
        List<PluginListDto> resList = new ArrayList<>();
        pluginManager.getPluginsMap().forEach((pluginId, pluginClass) -> {
            PluginListDto pluginListDto = new PluginListDto();
            pluginListDto.setId(pluginId);
            if (TransFlowInput.class.isAssignableFrom(pluginClass)) {
                pluginListDto.setType("input");
            } else if (TransFlowOutput.class.isAssignableFrom(pluginClass)) {
                pluginListDto.setType("output");
            } else if (TransFlowMiddleHandler.class.isAssignableFrom(pluginClass)) {
                pluginListDto.setType("gateway");
            }
            pluginListDto.setProperties(JobConfigProperties.getJobProperties(pluginClass));
            pluginListDto.setHandler(HandlerProperties.getHandler(pluginClass));
            resList.add(pluginListDto);
        });
        return Result.success(resList);
    }

}
